from time import sleep
import sys
from PyQt5.QtCore import QThread,pyqtSignal,QDateTime
from PyQt5.QtGui import QIcon,QPixmap,QImage
from PyQt5.QtWidgets import QMainWindow,QMessageBox,QInputDialog,QGridLayout,QWidget,QLabel,QComboBox,QPushButton,QLineEdit,QDesktopWidget,QApplication,QTextEdit,QFileDialog,QAction
from ctypes import windll
import base64
#系统配置
windll.shell32.SetCurrentProcessExplicitAppUserModelID("myappid")


class Timethread(QThread):

    update_date = pyqtSignal(str)

    def run(self):
        while True:
            data = QDateTime.currentDateTime()
            currtime = data.toString("hh:mm:ss")
            self.update_date.emit(str(currtime))
            sleep(1)


class BasemakeThread(QThread):

    fileload = ""
    Basetype = ""
    basetext_sinout = pyqtSignal(str)

    def run(self):
        try:
            imne = open(self.fileload, "rb")
            weas = imne.read()
            imne.close()

            if self.Basetype == "Base64":
                filebase = str(base64.b64encode(weas), encoding='UTF-8')

            elif self.Basetype == "Base32":
                filebase = str(base64.b32encode(weas), encoding='UTF-8')

            elif self.Basetype == "Base16":
                filebase = str(base64.b16encode(weas), encoding='UTF-8')

            elif self.Basetype == "Base85":
                filebase = str(base64.b85encode(weas), encoding='UTF-8')

            else:
                filebase = "无编码类型"

        except:
            filebase = "<font color='red'>编译错误或文件不存在，请检查后重试。</font>"
        
        self.basetext_sinout.emit(str(filebase))



class Window(QMainWindow):
    def __init__(self,parent=None):
        super(Window,self).__init__(parent)
        self.resize(700,530)

        #初始化窗口样式
        #self.setWindowFlags(Qt.FramelessWindowHint)
        #self.setWindowFlags(Qt.WindowMinimizeButtonHint)
        self.setWindowOpacity(0.90)

        self.status = self.statusBar()
        self.status.showMessage("~_~_~_~_~",8000)

        self.icobase1 = "AAABAAEAICAAAAAAAACoCAAAFgAAACgAAAAgAAAAQAAAAAEACAAAAAAAgAQAAAAAAAAAAAAAAAEAAAAAAAD///8AzP//AJn//wBm//8AM///AAD//wD/zP8AzMz/AJnM/wBmzP8AM8z/AADM/wD/mf8AzJn/AJmZ/wBmmf8AM5n/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wAAAAAA7gAAAN0AAAC7AAAAqgAAAIgAAAB3AAAAVQAAAEQAAAAiAAAAEQAA7gAAAN0AAAC7AAAAqgAAAIgAAAB3AAAAVQAAAEQAAAAiAAAAEQAA7gAAAN0AAAC7AAAAqgAAAIgAAAB3AAAAVQAAAEQAAAAiAAAAEQAAAO7u7gDd3d0Au7u7AKqqqgCIiIgAd3d3AFVVVQBEREQAIiIiABEREQAAAAAA////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////9vb39//////////////////////////////////////29vf3////////////////////////////////9vb29vb29/f39/f3///////////////////////////29vb29vb39/f39/f/////////////////////Vlb29vb29vb391ZW9/f39/f39/f/////Vlb///////9WVvb29vb29vf3Vlb39/f39/f39/////9WVv///////1ZW9vb39/f3/////1ZWVlb39/f39/f39///VlZWVv//Vlb29vf39/f/////VlZWVvf39/f39/f3//9WVlZW//9WVvf3/////1tbgID/////VlZWVvf39/f//1ZW/////1ZW9/f/////W1uAgP////9WVlZW9/f39///Vlb//////////1tbCwsREVtbgICAgP////9WVlZW////////////////W1sLCxERW1uAgICA/////1ZWVlb//////////zExMTFbW1tbW1sREQsLCwsREYCA////////////////MTExMVtbW1tbWxERCwsLCxERgID/////////////////////MTExMVtbW1tbW1tbCwtbW4CAgID///////////////8xMTExW1tbW1tbW1sLC1tbgICAgP////////////////////8xMTExCwsLCwsLW1v//////////////////////////zExMTELCwsLCwtbW////////////////////////////////zExW1v/////////////////////////////////////MTFbW////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////8P////D///8AD///AA//8AAA//AAAP/AAAADwAAAA8AAAAAAAAAAAAAAAMAAAADAAAADwAAAA8AAAAPAAAAD8AAAA/AAAAP/AAAP/wAAD//wAP//8AD///8P////D//////////////////////////////////"

        self.qrPixmap = QPixmap(QImage.fromData(base64.b64decode(self.icobase1)))
        self.setWindowIcon(QIcon(self.qrPixmap))
        self.setWindowTitle("MgBase")

        self.winwidth = 700
        self.winheight = 530
        self.center()

        #作者信息
        self.writer = "张熙果 ^ 希望给予保贵支持!"


        #菜单项
        mainlist = self.menuBar()

        #第一个主菜单
        caidan1 = mainlist.addMenu("菜单")

        writer = caidan1.addAction("作者信息")

        exetxt = caidan1.addAction("版本信息")

        deletetext = caidan1.addAction("清空文本框")
        deletetext.setShortcut("Ctrl+S")

        #一返回涵数
        caidan1.triggered[QAction].connect(self.menuback1)

        #第二个主菜单
        caidan2 = mainlist.addMenu("颜色与视觉")

        btcolor = caidan2.addMenu("代码框")
        btcolor.addAction("棕米-黑色 (默认)")
        btcolor.addSeparator()
        btcolor.addAction("黑-白色")
        btcolor.addAction("黑-天蓝色")
        btcolor.addAction("黑-绿色")
        btcolor.addAction("黑-黄色")
        btcolor.addSeparator()
        btcolor.addAction("白-黑色")
        btcolor.addAction("白-蓝色")
        btcolor.addAction("白-绿色")
        btcolor.addAction("白-紫色")


        # 二返回涵数
        caidan2.triggered[QAction].connect(self.menuback2)

        caidan3 = mainlist.addMenu("帮助与信息")
        caidan3.addAction("使用须知")

        #三返回涵数
        caidan3.triggered[QAction].connect(self.menuback3)



        self.label_t1 = QLabel(self)
        self.setObjectName("label1QLabel")
        self.label_t1.setText('<p align="left"><font>文件路径： </font></p>')
        self.label_t1.setAutoFillBackground(True)
        self.label_t1.setStyleSheet("font: 75 15pt '微软雅黑';"
                                    "border:1px outset rgb(20, 0, 150); "
                                    "color: rgb(50, 120, 220); "
                                    "background-color:khaki; "
                                    "font-weight:bold;"
                                    )


        self.e1 = QLineEdit(self)
        self.e1.setPlaceholderText('请输入文件路径...')
        self.e1.setStyleSheet("font-size:18px; color:black; background-color:rgb(175,238,238); font-family:Arial")


        self.label_t2 = QLabel(self)
        self.setObjectName("label2")
        self.label_t2.setText('<p align="left"><font>操作类型： </font></p>')
        self.label_t2.setAutoFillBackground(True)
        self.label_t2.setStyleSheet("font: 75 15pt '微软雅黑';"
                                    "border:1px outset rgb(0, 0, 0); "
                                    "color: grey; "
                                    "background-color:white; "
                                    "font-weight:bold;"
                                    )

        self.b1 = QPushButton(self)
        self.b1.setText("文件转变成编码")
        self.b1.setDefault(True)
        self.b1.setStyleSheet("font-size:15px; font-family:微软雅黑")
        self.b1.clicked.connect(self.b1_clicked)

        self.b2 = QPushButton(self)
        self.b2.setText("选择文件")
        self.b2.setDefault(True)
        self.b2.setStyleSheet("font-size:15px; font-family:楷体")
        self.b2.clicked.connect(self.b2_clicked)

        self.b3 = QPushButton(self)
        self.b3.setText("编译为文件")
        self.b3.setDefault(True)
        self.b3.setStyleSheet('font: 75 11pt "微软雅黑"')

        self.b3.clicked.connect(self.b3_clicked)

        self.label_t3 = QLabel(self)
        self.label_t3.setText('<p align="left"><font>|  *^*  |</font></p>')
        self.label_t3.setAutoFillBackground(True)
        self.label_t3.setStyleSheet(
            "color:white; background-color:'sky blue'; font-size:30px; font-weight:normal; font-family:楷体;")

        self.b4 = QPushButton(self)
        self.b4.setText("复制代码")
        self.b4.setDefault(True)
        self.b4.setStyleSheet("font-size:15px; font-family:微软雅黑")
        self.b4.clicked.connect(self.b4_clicked)

        self.label_t4 = QLabel(self)
        self.label_t4.setText('编码类型')
        self.label_t4.setAutoFillBackground(True)
        self.label_t4.setStyleSheet("font: 70 14pt '微软雅黑';"
                                    "border:1px outset rgb(20, 0, 150); "
                                    "color: rgb(50, 120, 220); "
                                    "background-color:black; "
                                    "font-weight:bold;"
                                    )

        self.cb = QComboBox(self)
        self.cb.setObjectName("baseQComboBox")
        self.cb.addItem("Base64")
        self.cb.addItem("Base32")
        self.cb.addItem("Base16")
        self.cb.addItem("Base85")
        self.cb.currentIndexChanged.connect(self.cbindexchange)



        # base代码表#F5F5DC
        self.basetext = QTextEdit(self)
        self.basetext.setPlainText("")
        self.basetext.setStyleSheet('font-size:13px; font-family:微软雅黑; background-color:"white"')

        # 控件布局
        vlayout = QGridLayout(self)
        vlayout.addWidget(self.label_t1, 1, 1, 1, 1)
        vlayout.addWidget(self.e1, 1, 2, 1, 5)
        vlayout.addWidget(self.label_t4,1,7,1,1)
        vlayout.addWidget(self.label_t2,2,1,1,1)
        vlayout.addWidget(self.b1,2,2,1,1)
        vlayout.addWidget(self.b3,2,3,1,1)
        vlayout.addWidget(self.label_t3,2,4,1,1)
        vlayout.addWidget(self.b4,2,5,1,1)
        vlayout.addWidget(self.b2,2,6,1,1)
        vlayout.addWidget(self.cb,2,7,1,1)
        vlayout.addWidget(self.basetext,3,1,1,7)

        widget = QWidget()
        widget.setLayout(vlayout)
        self.setCentralWidget(widget)
        # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 多线程区 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#

        #####################################################
        # 时间更新多线程
        self.backend = Timethread()
        self.backend.update_date.connect(self.Wintitletime)
        self.backend.start()

    # 多线程和控件update事件
    def Wintitletime(self,data):
        self.setWindowTitle("MgBase @ "+str(data))

    def basetextupdate(self,text):
        self.basetext.setText(text)
        self.b1.setEnabled(True)
        self.update()


    #标准事件与涵数
    def center(self):
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.wx = (screen.width() - size.width()) / 2
        self.wy = (screen.height() - size.height()) / 2

        #self.setSize(self.winwidth, self.winheight)
        self.setFixedSize(self.winwidth, self.winheight)

        self.move(int(self.wx), int(self.wy))

    def menuback1(self,bud):

        cmdtext = bud.text()
        if cmdtext == "作者信息":
            QMessageBox.information(self, "作者信息", "<font color='purple' size='4'>"+str(self.writer)+"</font>", QMessageBox.Yes, QMessageBox.Yes)

        elif cmdtext == "版本信息":
            QMessageBox.warning(self, "版本信息", "<font color='#B22222' size='4'>MgBase | Base编码转换程序 | </font>", QMessageBox.Yes, QMessageBox.Yes)

        elif cmdtext == "清空文本框":
            self.basetext.clear()
            self.update()

        else:
            QMessageBox.warning(self, "Nothing", "此服务暂未开通。", QMessageBox.Yes, QMessageBox.Yes)

    def menuback2(self, bud):

        cmdtext = bud.text()
        if cmdtext == "棕米-黑色 (默认)":
            self.basetext.setStyleSheet('font-size:13px; font-family:微软雅黑; background-color:"khaki"; color:"black"')
            self.status.showMessage("设置成功。", 3000)
            self.update()

        ###########################
        elif cmdtext == "黑-白色":
            self.basetext.setStyleSheet('font-size:13px; font-family:微软雅黑; background-color:"black"; color:"white"')
            self.status.showMessage("设置成功。", 3000)
            self.update()

        elif cmdtext == "黑-天蓝色":
            self.basetext.setStyleSheet('font-size:13px; font-family:微软雅黑; background-color:"black"; color:"sky blue"')
            self.status.showMessage("设置成功。", 3000)
            self.update()

        elif cmdtext == "黑-绿色":
            self.basetext.setStyleSheet('font-size:13px; font-family:微软雅黑; background-color:"black"; color:"light green"')
            self.status.showMessage("设置成功。", 3000)
            self.update()

        elif cmdtext == "黑-黄色":
            self.basetext.setStyleSheet('font-size:13px; font-family:微软雅黑; background-color:"black"; color:"yellow"')
            self.status.showMessage("设置成功。", 3000)
            self.update()


        ####################################
        elif cmdtext == "白-黑色":
            self.basetext.setStyleSheet('font-size:13px; font-family:微软雅黑; background-color:"white"; color:"black"')
            self.status.showMessage("设置成功。", 3000)
            self.update()

        elif cmdtext == "白-蓝色":
            self.basetext.setStyleSheet('font-size:13px; font-family:微软雅黑; background-color:"white"; color:"blue"')
            self.status.showMessage("设置成功。", 3000)
            self.update()

        elif cmdtext == "白-绿色":
            self.basetext.setStyleSheet('font-size:13px; font-family:微软雅黑; background-color:"white"; color:"green"')
            self.status.showMessage("设置成功。", 3000)
            self.update()

        elif cmdtext == "白-紫色":
            self.basetext.setStyleSheet('font-size:13px; font-family:微软雅黑; background-color:"white"; color:"purple"')
            self.status.showMessage("设置成功。", 3000)
            self.update()

    def menuback3(self,bud):
        text = "<font color='black' size='5' face='楷体'>这个Base编码转换程序可转换大多数文件，程序采用多线程转码，但如果文件过大还是可能会导制程序无响应或者程序卡死（有时等待一会即可恢复）。 希望使用者们千万不要让它吃的太饱哦~</font>"
        QMessageBox.warning(self, "使用须知", text, QMessageBox.Yes, QMessageBox.Yes)



        '''
        if cmdtext=="窗口缩放":
            screen = self.geometry()

            self.changceheight = 600
            nowhight = self.height()

            if self.winheight == nowhight:
                starthight = self.winheight
                endhight = self.changceheight
                self.basetext.setGeometry(10, 100, 580, 470 )

            else:
                starthight = self.changceheight
                endhight = self.winheight
                self.basetext.setGeometry(10, 100, 580, 400 )

            self.animation = QPropertyAnimation(self,b'geometry')
            self.animation.setDuration(500)
            self.animation.setStartValue(QRect(int(screen.x()),int(screen.y()),self.winwidth,starthight))
            self.animation.setEndValue(QRect(int(screen.x()),int(screen.y()),self.winwidth,endhight))
            self.animation.start()


            print(screen.x(),screen.y())
        '''

    def b1_clicked(self):
        self.fileurl = str(self.e1.text())
        if len(self.fileurl) == 0 or len(self.fileurl) < 7:
            self.basetext.setText("<font color='red'>错误的路径格式...请检查后重试</font>")

        else:

            self.b1.setEnabled(False)
            self.Basemake = BasemakeThread()
            self.Basemake.fileload = self.fileurl
            self.Basemake.Basetype = self.cb.currentText()
            self.Basemake.basetext_sinout.connect(self.basetextupdate)
            self.Basemake.start()



    def b2_clicked(self):
        fname = QFileDialog.getOpenFileName(self,'选择文件',"","all files (*.*)")
        self.e1.setText(str(fname[0]))

    def b3_clicked(self):
        basetxt = self.basetext.toPlainText()
        if len(basetxt) < 50:
            QMessageBox.critical(self, "错误", "base格式错误，请检查后重试。", QMessageBox.Yes, QMessageBox.Yes)

        else:
            try:
                basetype = self.cb.currentText()
                if basetype == "Base64":
                    unbase = base64.b64decode(basetxt)

                elif basetype == "Base32":
                    unbase = base64.b32decode(basetxt)

                elif basetype == "Base16":
                    unbase = base64.b16decode(basetxt)

                elif basetype == "Base85":
                    unbase = base64.b85decode(basetxt)

                else:
                    unbase = "nothing"

                fname,ok = QInputDialog.getText(self,'请输入编译后的文件名：','文件名.后缀 例：file.png 文件将保存在本程序文件夹下')
                if ok:

                    imne2 = open('./'+str(fname), "wb")
                    imne2.write(unbase)
                    imne2.close()

                self.status.showMessage("文件已生成，保存在本程序目录下。", 5000)

            except:
                QMessageBox.critical(self,"错误","文件生成错误，请检查后重试。",QMessageBox.Yes,QMessageBox.Yes)

    def b4_clicked(self):
        clip = QApplication.clipboard()
        clip.setText(self.basetext.toPlainText())


    def cbindexchange(self,i):
        print(str(i)+self.cb.itemText(i))


    def closeEvent(self, event):
        QMessageBox.information(self,"关闭语","Mgbase 欢迎您再次使用.",QMessageBox.Yes,QMessageBox.Yes)


if __name__ == "__main__":
    app = QApplication(sys.argv)

    win = Window()

    qssbase = '''
        QLineEdit::hover{border:2px inset rgb(218, 165, 32);}
    
        QPushButton::hover{
            border:2px inset rgb(95, 158, 160);
            color: rgb(80, 79, 180);
            }
        
        QComboBox#baseQComboBox {
            font: 75 12pt "微软雅黑";
            font-weight:bold;
            color: rgb(95, 166, 186);

            border:1px inset gray;
            }
    
        QComboBox#baseQComboBox::hover{
            border:1px inset rgb(20, 175, 231);
            color: rgb(95, 166, 186);
            }
        
        QComboBox#baseQComboBox QAbstractItemView {
            color: rgb(95, 166, 186);
            selection-color: rgb(100, 0, 255);
            selection-background-color: rgb(193, 242, 232, 143);
            }

    '''

    win.setStyleSheet(qssbase)


    win.show()

    sys.exit(app.exec_())







